<?php
/**
 * 
 * Base (前台公共模块)
 *
 * @package      	YOURPHP
 * @author          liuxun QQ:147613338 <admin@yourphp.cn>
 * @copyright     	Copyright (c) 2008-2011  (http://www.yourphp.cn)
 * @license         http://www.yourphp.cn/license.txt
 * @version        	YourPHP企业网站管理系统 v2.1 2011-03-01 yourphp.cn $
 */
if(!defined("Yourphp")) exit("Access Denied");
class BaseAction extends Action
{
	protected   $Config ,$sysConfig,$categorys,$module,$moduleid,$mod,$dao,$Type,$Role,$_userid,$_groupid,$_email,$_username ,$forward ,$user_menu,$Lang,$member_config,$modulearr,$_realname,$_islogin,$_islong,$_ms,$_xue_u,$url1;
    public function _initialize() {
		// if($this->_isLogin = 'false'){
        //     cookie('hgkjjy',null);
		// 	cookie('hgkjjy','');
        // }
			$this->sysConfig = F('sys.config');
		//echo GROUP_NAME.MODULE_NAME.ACTION_NAME;
			$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
			$severname=$_SERVER["SERVER_NAME"];
			if($severname!='stu.fjhgkj.com.cn')
			{ 
				$yourphp_auth_key = sysmd5($this->sysConfig['ADMIN_ACCESS'].$_SERVER['HTTP_USER_AGENT']);
				if(!cookie('xue_u'))
				{
					//$uau=M('user')->field('id,groupid,password,avatar,realname')->where(array('web_url'=>array('LIKE',$severname)))->find();
                    $xxxx = json_decode($this->http('http://user.fjhgkj.com.cn/index.php?m=Home&c=index&a=url_info',array('severname'=>$severname)) ,'true') ;
                    $uau['avatar'] = $xxxx['img'] ;
                    $uau['realname'] = $xxxx['name'] ;
                    $uau['groupid'] = $xxxx['role_id'] ;
                    $uau['password'] = $xxxx['login_pwd'] ;
                    $uau['id'] = $xxxx['id'] ;
					//print_r($uau);
					$xue_u_cc = authcode($uau['avatar']."-".$uau['realname'], 'ENCODE', $yourphp_auth_key);
					cookie('xue_u',$xue_u_cc);
					$yourphp_auth = authcode($uau['id']."-".$uau['groupid']."-".$uau['password'], 'ENCODE', $yourphp_auth_key);
					cookie('auth',$yourphp_auth);
				}
				$this->_xue_u=list($avatar,$realname) = explode("-", authcode(cookie('xue_u'), 'DECODE', $yourphp_auth_key));
			}
			else
			{
				$this->_xue_u=array();
				cookie('xue_u',null);
			}
			$url= $_SERVER["REQUEST_SCHEME"].'://'.$severname.':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
                        $this->url1 = $url ;
                        if($_SERVER["REQUEST_URI"] == '/index.php?g=User&m=Login&a=logout'){
                           $this->url1 =  $_SERVER["REQUEST_SCHEME"].'://'.$severname.':'.$_SERVER["SERVER_PORT"].'/index.php?g=User&m=Student&a=visited' ;
                        }
                        $this->assign('url1', urlencode($this->url1));
			//echo $severname;

			if ((strpos($agent, 'mobile'))) {
                            if (GROUP_NAME == "Home" && ACTION_NAME == 'detailsplay') {

                                if (strpos($url, 'detailsplay') !== false) {
                                    $url = str_replace("detailsplay", "detailsplaymobile", $url);
                                }
                                redirect($url);
                            }
                        }

			$this->modulearr=M('module')->select();
			$this->_islogin='false';
			$this->_islong='false';

			 
			$this->module = F('Module');
			$this->Role = F('Role');
			$this->Type =F('Type');
			$this->mod= F('Mod');
			$this->moduleid=$this->mod[MODULE_NAME];
			if(APP_LANG){
				$this->Lang = F('Lang');
				$this->assign('Lang',$this->Lang);
				if(get_safe_replace($_GET['l'])){
					if(!$this->Lang[$_GET['l']]['status'])$this->error ( L ( 'NO_LANG' ) );
					$lang=$_GET['l'];
				}else{
					$lang=$this->sysConfig['DEFAULT_LANG'];
				}
				define('LANG_NAME', $lang);
				define('LANG_ID', $this->Lang[$lang]['id']);
				$this->categorys = F('Category_'.$lang);
				$this->Config = F('Config_'.$lang);
				$this->assign('l',$lang);
				$this->assign('langid',LANG_ID);
				$T = F('config_'.$lang,'', APP_PATH.'Tpl/Home/'.$this->sysConfig['DEFAULT_THEME'].'/');
				C('TMPL_CACHFILE_SUFFIX','_'.$lang.'.php');
				cookie('think_language',$lang);
			}else{
				$T = F('config_'.$this->sysConfig['DEFAULT_LANG'],'',  APP_PATH.'Tpl/Home/'.$this->sysConfig['DEFAULT_THEME'].'/');
				$this->categorys = F('Category');
				$this->Config = F('Config');
				cookie('think_language',$this->sysConfig['DEFAULT_LANG']);
			}
			$this->assign('T',$T);
			$this->assign($this->Config);
			$this->assign('Role',$this->Role);
			$this->assign('Type',$this->Type);
			$this->assign('Module',$this->module);
			$this->assign('Categorys',$this->categorys);
			import("@.ORG.Form");			
			$this->assign ( 'form',new Form());
			C('HOME_ISHTML',$this->sysConfig['HOME_ISHTML']);
			C('PAGE_LISTROWS',$this->sysConfig['PAGE_LISTROWS']);
			C('URL_M',$this->sysConfig['URL_MODEL']);
			C('URL_M_PATHINFO_DEPR',$this->sysConfig['URL_PATHINFO_DEPR']);
			C('URL_M_HTML_SUFFIX',$this->sysConfig['URL_HTML_SUFFIX']);
			C('URL_LANG',$this->sysConfig['DEFAULT_LANG']);
			C('DEFAULT_THEME_NAME',$this->sysConfig['DEFAULT_THEME']);
			if($_COOKIE['hgkjjy']){
				//单点登录
				$hg_user = json_decode($_COOKIE['hgkjjy'],true);
				$this->_userid = $hg_user['id'];
				$this->_username =  $hg_user['login_name'];
				$this->_groupid = $hg_user['type'];
				$this->_email =  $hg_user['email'];
				$user=M('user')->where(array('id'=>$this->_userid))->find();
				if($hg_user['id'])
				{
                    $hkhk = json_decode($this->http('http://user.fjhgkj.com.cn/index.php?m=Home&c=Index&a=get_username',array('id'=>$hg_user['id'],'type'=>$hg_user['type'])) ,'true') ;
					$this->_realname = $hkhk['name'];
					$this->_islogin='true';
					$this->_islong=iconv_strlen($hkhk['name'],"utf-8")>8 ? true : false;
					$this->assign('realname',$hkhk['name']);
                    $this->assign('avatar',$hkhk['img']);
					 
				}
				else
				{
				$this->_groupid = cookie('groupid') ?  cookie('groupid') : 4;
				$this->_userid =0;
			    }
		    }
			// else if(cookie('auth')){
			// 	$this->_userid = cookie('userid');
			// 	$this->_username =  cookie('username');
			// 	$this->_groupid = cookie('groupid'); 
			// 	$this->_email =  cookie('email');
			// 	$user=M('user')->where(array('id'=>$this->_userid))->find();
			// 	if(cookie('userid'))
			// 	{
            //         $hkhk = json_decode($this->http('http://user.fjhgkj.com.cn/index.php?m=Home&c=Index&a=get_username',array('id'=>cookie('userid'),'type'=>cookie('groupid'))) ,'true') ;
			// 		$this->_realname = $hkhk['name'];
			// 		$this->_islogin='true';
			// 		$this->assign('realname',$hkhk['name']);
            //         $this->assign('avatar',cookie('avatar'));
					 
			// 	}
			// }else{
			// 	$this->_groupid = cookie('groupid') ?  cookie('groupid') : 4;
			// 	$this->_userid =0;
			// }


			foreach((array)$this->module as $r){
				if($r['issearch'])$search_module[$r['name']] = L($r['name']);
				if($r['ispost'] && (in_array($this->_groupid,explode(',',$r['postgroup']))))$this->user_menu[$r['id']]=$r;
			}
			if(GROUP_NAME=='User'){
				$langext = $lang ? '_'.$lang : '';
				$this->member_config=F('member.config'.$langext);
				$this->assign('member_config',$this->member_config);
				$this->assign('user_menu',$this->user_menu);
				if($this->_groupid=='5' &&  MODULE_NAME!='Login'){ 
					$this->assign('jumpUrl',URL('User-Login/emailcheck'));
					$this->assign('waitSecond',3);
					$this->success(L('no_regcheckemail'));
					exit;
				}
				$this->assign('header',TMPL_PATH.'Home/'.THEME_NAME.'/Home_header.html');
			}
			if($_GET['forward'] || $_POST['forward']){	
				$this->forward = get_safe_replace($_GET['forward'].$_POST['forward']);
			}else{
				if(MODULE_NAME!='Register' || MODULE_NAME!='Login' )
				$this->forward =isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] :  $this->Config['site_url'];
			}
			$this->_ms='0';//游客
			switch ($this->_groupid) {
				case '1':
					$this->_ms='1';//学校、企业
					break;
				
				case '2':
					$this->_ms='2';//老师
					break;
				case '3':
					$this->_ms='3';//学生
					break;
				//case '1':
				//	$this->_ms='4';//企业
				//	break;
			}
			$urll = M('article')->field('id,title,catid')->select();
			$this->assign('urll',$urll);
			$this->assign('ms',$this->_ms);
			$this->assign('xue_u',$this->_xue_u);
			$this->assign('forward',$this->forward);
			$this->assign('islogin',$this->_islogin);
			$this->assign('islong',$this->_islong);
			$this->assign('search_module',$search_module);
			$this->assign('module_name',MODULE_NAME);
			$this->assign('action_name',ACTION_NAME);
                        
 
	}

    public function index($catid='',$module='')
    {
		$this->Urlrule =F('Urlrule');
		if(empty($catid)) $catid =  intval($_REQUEST['id']);
		$p= max(intval($_REQUEST[C('VAR_PAGE')]),1);
		if($catid){
			$cat = $this->categorys[$catid];
			$bcid = explode(",",$cat['arrparentid']); 
			$bcid = $bcid[1]; 
			if($bcid == '') $bcid=intval($catid);
			if(empty($module))$module=$cat['module'];
			$this->assign('module_name',$module);
			unset($cat['id']);
			$this->assign($cat);
			$cat['id']=$catid;
			$this->assign('catid',$catid);
			$this->assign('bcid',$bcid);
		}
		if($cat['readgroup'] && $this->_groupid!=1 && !in_array($this->_groupid,explode(',',$cat['readgroup']))){$this->assign('jumpUrl',URL('User-Login/index'));$this->error (L('NO_READ'));}
		$fields = F($this->mod[$module].'_Field');
		foreach($fields as $key=>$r){
			$fields[$key]['setup'] =string2array($fields[$key]['setup']);
		}
		$this->assign ( 'fields', $fields); 


		$seo_title = $cat['title'] ? $cat['title'] : $cat['catname'];
		$this->assign ('seo_title',$seo_title);
		$this->assign ('seo_keywords',$cat['keywords']);
		$this->assign ('seo_description',$cat['description']);
				

		if($module=='Guestbook'){
			$where['status']=array('eq',1);
			$this->dao= M($module);
			$count = $this->dao->where($where)->count();
			if($count){
				import ( "@.ORG.Page" );
				$listRows =  !empty($cat['pagesize']) ? $cat['pagesize'] : C('PAGE_LISTROWS');		
				$page = new Page ( $count, $listRows );
				$page->urlrule = geturl($cat,'');
				$pages = $page->show();
				$field =  $this->module[$cat['moduleid']]['listfields'];
				$field =  $field ? $field : '*';
				$list = $this->dao->field($field)->where($where)->order('createtime desc,id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
				$this->assign('pages',$pages);
				$this->assign('list',$list);
			}
			$template = $cat['module']=='Guestbook' && $cat['template_list'] ? $cat['template_list'] : 'index';
			$this->display(THEME_PATH.$module.'_'.$template.'.html');
		}elseif($module=='Feedback'){
			$template = $cat['module']=='Feedback' && $cat['template_list'] ? $cat['template_list'] : 'index' ;

			$this->display(THEME_PATH.$module.'_'.$template.'.html');
		}elseif($module=='Page'){
			$modle=M('Page');
			$data = $modle->find($catid);
			unset($data['id']);

			//分页
			$CONTENT_POS = strpos($data['content'], '[page]');
			if($CONTENT_POS !== false) {			
				$urlrule = geturl($cat,'',$this->Urlrule);
				$urlrule[0] =  urldecode($urlrule[0]);
				$urlrule[1] =  urldecode($urlrule[1]);
				$contents = array_filter(explode('[page]',$data['content']));
				$pagenumber = count($contents);
				for($i=1; $i<=$pagenumber; $i++) {
					$pageurls[$i] = str_replace('{$page}',$i,$urlrule);
				} 
				$pages = content_pages($pagenumber,$p, $pageurls);
				//判断[page]出现的位置
				if($CONTENT_POS<7) {
					$data['content'] = $contents[$p];
				} else {
					$data['content'] = $contents[$p-1];
				}
				$this->assign ('pages',$pages);	
			}

			$template = $cat['template_list'] ? $cat['template_list'] :  'index' ;
			$this->assign ($data);	
			$this->display(THEME_PATH.$module.'_'.$template.'.html');

		}else{
			
			if($catid){
				$seo_title = $cat['title'] ? $cat['title'] : $cat['catname'];
				$this->assign ('seo_title',$seo_title);
				$this->assign ('seo_keywords',$cat['keywords']);
				$this->assign ('seo_description',$cat['description']);
				

				$where = " status=1 ";
				if($cat['child']){							
					$where .= " and catid in(".$cat['arrchildid'].")";			
				}else{
					$where .=  " and catid=".$catid;			
				}
				if(empty($cat['listtype'])){
					$this->dao= M($module);
					$count = $this->dao->where($where)->count();
					if($count){
						import ( "@.ORG.Page" );
						$listRows =  !empty($cat['pagesize']) ? $cat['pagesize'] : C('PAGE_LISTROWS');
						$page = new Page ( $count, $listRows );
						$page->urlrule = geturl($cat,'',$this->Urlrule);
						$pages = $page->show();
						$field =  $this->module[$this->mod[$module]]['listfields'];
						$field =  $field ? $field : 'id,catid,userid,url,username,title,title_style,keywords,description,thumb,createtime,hits';
						$list = $this->dao->field($field)->where($where)->order('createtime desc,id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
						$this->assign('pages',$pages);
						$this->assign('list',$list);
					}
					$template_r = 'list';
				}else{
					$template_r = 'index';
				}
			}else{
				$template_r = 'list';
			}
			$template = $cat['template_list'] ? $cat['template_list'] : $template_r;
			$this->display($module.':'.$template);
		}
    }

 

	public function show($id='',$module='')
    {
		$this->Urlrule =F('Urlrule');
		$p= max(intval($_REQUEST[C('VAR_PAGE')]),1);		
		$id = $id ? $id : intval($_REQUEST['id']);
		$module = $module ? $module : MODULE_NAME;
		$this->assign('module_name',$module);
		$this->dao= M($module);;
		$data = $this->dao->find($id);
		
		
		$catid = $data['catid'];
		$cat = $this->categorys[$data['catid']];
		if(empty($cat['ishtml']))$this->dao->where("id=".$id)->setInc('hits'); //添加点击次数
		$bcid = explode(",",$cat['arrparentid']); 
		$bcid = $bcid[1]; 
		if($bcid == '') $bcid=intval($catid);

		if($data['readgroup']){
			if($this->_groupid!=1 && !in_array($this->_groupid,explode(',',$data['readgroup'])) )$noread=1;
		}elseif($cat['readgroup']){
			if($this->_groupid!=1 && !in_array($this->_groupid,explode(',',$cat['readgroup'])) )$noread=1;
		}
		if($noread==1){$this->assign('jumpUrl',URL('User-Login/index'));$this->error (L('NO_READ'));}

		$chargepoint = $data['readpoint'] ? $data['readpoint'] : $cat['chargepoint']; 
		if($chargepoint && $data['userid'] !=$this->_userid){
			$user = M('User');
			$userdata =$user->find($this->_userid);
			
			if($cat['paytype']==1 && $userdata['point']>=$chargepoint){
				$chargepointok = $user->where("id=".$this->_userid)->setDec('point',$chargepoint);
			}elseif($cat['paytype']==2 && $userdata['amount']>=$chargepoint){
				$chargepointok = $user->where("id=".$this->_userid)->setDec('amount',$chargepoint);
			}else{
				$this->error (L('NO_READ'));
			}
		}
	
		$seo_title = $data['title'].'-'.$cat['catname'];
		$this->assign ('seo_title',$seo_title);
		$this->assign ('seo_keywords',$data['keywords']);
		$this->assign ('seo_description',$data['description']);
		$this->assign ( 'fields', F($cat['moduleid'].'_Field') ); 
		

		$fields = F($this->mod[$module].'_Field');
		foreach($data as $key=>$c_d){
			$setup='';
			$fields[$key]['setup'] =$setup=string2array($fields[$key]['setup']);
			if($setup['fieldtype']=='varchar' && $fields[$key]['type']!='text'){
				$data[$key.'_old_val'] =$data[$key];
				$data[$key]=fieldoption($fields[$key],$data[$key]);
			}elseif($fields[$key]['type']=='images' || $fields[$key]['type']=='files'){ 
				if(!empty($data[$key])){
					$p_data=explode(':::',$data[$key]);
					$data[$key]=array();
					foreach($p_data as $k=>$res){
						$p_data_arr=explode('|',$res);					
						$data[$key][$k]['filepath'] = $p_data_arr[0];
						$data[$key][$k]['filename'] = $p_data_arr[1];
					}
					unset($p_data);
					unset($p_data_arr);
				}
			}
			unset($setup);
		}
		$this->assign('fields',$fields); 


		//手动分页
		$CONTENT_POS = strpos($data['content'], '[page]');
		if($CONTENT_POS !== false) {
			
			$urlrule = geturl($cat,$data,$this->Urlrule);
			$urlrule =  str_replace('%7B%24page%7D','{$page}',$urlrule); 
			$contents = array_filter(explode('[page]',$data['content']));
			$pagenumber = count($contents);
			for($i=1; $i<=$pagenumber; $i++) {
				$pageurls[$i] = str_replace('{$page}',$i,$urlrule);
			} 
			$pages = content_pages($pagenumber,$p, $pageurls);
			//判断[page]出现的位置是否在文章开始
			if($CONTENT_POS<7) {
				$data['content'] = $contents[$p];
			} else {
				$data['content'] = $contents[$p-1];
			}
			$this->assign ('pages',$pages);	
		}

		if(!empty($data['template'])){
			$template = $data['template'];
		}elseif(!empty($cat['template_show'])){
			$template = $cat['template_show'];
		}else{
			$template =  'show';
		}

		$this->assign('catid',$catid);
		$this->assign ($cat);
		$this->assign('bcid',$bcid);

		$this->assign ($data);

		$this->display($module.':'.$template); 
    }

	public function down()
	{

		$module = $module ? $module : MODULE_NAME;
		$id = $id ? $id : intval($_REQUEST['id']);
		$this->dao= M($module);
		$filepath = $this->dao->where("id=".$id)->getField('file');
		$this->dao->where("id=".$id)->setInc('downs');

		if(strpos($filepath, ':/')) { 
			header("Location: $filepath");
		} else {	
			$filepath = '.'.$filepath;
			if(!$filename) $filename = basename($filepath);
			$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
			if(strpos($useragent, 'msie ') !== false) $filename = rawurlencode($filename);
			$filetype = strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
			$filesize = sprintf("%u", filesize($filepath));
			if(ob_get_length() !== false) @ob_end_clean();
			header('Pragma: public');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
			header('Cache-Control: no-store, no-cache, must-revalidate');
			header('Cache-Control: pre-check=0, post-check=0, max-age=0');
			header('Content-Transfer-Encoding: binary');
			header('Content-Encoding: none');
			header('Content-type: '.$filetype);
			header('Content-Disposition: attachment; filename="'.$filename.'"');
			header('Content-length: '.$filesize);
			readfile($filepath);
		}
		exit;
	}

	public function hits()
	{
		$module = $module ? $module : MODULE_NAME;
		$id = $id ? $id : intval($_REQUEST['id']);
		$this->dao= M($module);
		$this->dao->where("id=".$id)->setInc('hits');

		if($module=='Download'){
			$r = $this->dao->find($id);
			echo '$("#hits").html('.$r['hits'].');$("#downs").html('.$r['downs'].');';
		}else{
			$hits = $this->dao->where("id=".$id)->getField('hits');
			echo '$("#hits").html('.$hits.');';
		}
		exit;
	}
	public function verify()
    {
		header('Content-type: image/jpeg');
        $type	 =	 isset($_GET['type'])? get_safe_replace($_GET['type']):'jpeg';
        import("@.ORG.Image");
        Image::buildImageVerify(4,1,$type);
	}
	function number2Chinese($num, $m = 1) {
		switch($m) {
			case 0:
				$CNum = array(
					array('零','壹','贰','叁','肆','伍','陆','柒','捌','玖'),
					array('','拾','佰','仟'),
					array('','萬','億','萬億')
				);
			break;
			default:
				$CNum = array(
					array('零','一','二','三','四','五','六','七','八','九'),
					array('','十','百','千'),
					array('','万','亿','万亿')
				);
			break;
		}
	
		if (!is_numeric($num)) {
			return false;
		}
		$flt = '';
		if (is_integer($num)) {
			$num = strval($num);
		}else if(is_numeric($num)){
			$num = strval($num);
			$rs = explode('.',$num,2);
			$num = $rs[0];
			$flt = $rs[1];
		}
	
		$len = strlen($num);
		$tempnum=$num;//补救10的问题
		$num = strrev($num);
		$chinese = '';
		
		for($i = 0,$k=0;$i < $len; $i+=4,$k++){
			$tmp_str = '';
			$str = strrev(substr($num , $i,4));
			$str = str_pad($str,4,'0',STR_PAD_LEFT);
			for ($j = 0; $j < 4; $j++) { 
				if($str{$j} !== '0'){
					$tmp_str .= $CNum[0][$str{$j}] . $CNum[1][4-1-$j];
				}
			}
			$tmp_str .= $CNum[2][$k];
			$chinese = $tmp_str . $chinese;
			unset($str);
		}
		if($flt !== ''){
			$str = '';
			for ($i=0; $i < strlen($flt); $i++) { 
				$str .= $CNum[0][$flt{$i}];
			}
			$chinese .= "点{$str}";
		}
	
		if($tempnum>=11&&$tempnum<=19)
		{
			$chinese=mb_substr($chinese,1,2,'utf-8');
		}
		if($tempnum==10)
		{
			$chinese='十';
		}
		return $chinese;
	}
	//id查看表名
	public function modulefind($id)
	{
		foreach ($this->modulearr as $key2 => $value2) {
			if($value2['id']==$id)
			{
				$mname=strtolower($value2['name']);
			}
		}
		unset($value2);
		return $mname;
	}
	//获取数据 
	public function pushnewarr($id,$arr,$isarr=true)
	{
		$result=array();
		if($isarr)
		{
			$fie=array();
			$fieldarr=M('field')->where(array('moduleid'=>array('in','13,12,14,23,22,21,24,25')))->select();
			foreach ($fieldarr as $key => $value) {
				if($value['moduleid']==$id)
				{
					//array_push($fie,array('id'=>$value['moduleid'],'name'=>$value['field']));
					array_push($fie,$value);
				}
				unset($value);
			}
			 
			foreach ($arr as $key => $value) {
				$a=array();
				foreach ($value as $key2 => $value2) {
					$geta=$this->getfield($fie,$key2);
					
					if($geta)
					{
						//$a=array($key2=>array('val'=>$value2,'attr'=>$geta));
						$a[$key2]=array('val'=>$value2,'attr'=>$geta);
						//array_push($a,array($key2=>array('val'=>$value2,'attr'=>$geta)));
					}else
					{
						$a[$key2]=array('val'=>$value2);
						//array_push($a,array($key2=>array('val'=>$value2)));
						//$a=array($key2=>array('val'=>$value2));
					}
					
					
				}
				array_push($result,$a);
				unset($value2);
				unset($a);
			}
			unset($value);
		}else
		{
			foreach ($arr as $key => $value) {
				$a=array();
				foreach ($value as $key2 => $value2) {
					$a[$key2]=array('val'=>$value2);
				}
				array_push($result,$a);
				unset($value2);
				unset($a);
			}
			unset($value);
		}
		return $result;
	}
	//查看键名
	public function getfield($fie,$name)
	{
		$result=array();
		foreach ($fie as $key => $value) {
			if($value['field']==$name)
			{
				$result=$value;
			}
		}
		unset($value);
		return $result;
	}
	// public function getmodid($str)
	// {
	// 	$a='';
	// 	switch ($str) {
	// 		case 'zy':
	// 			# code...
	// 			break;
	// 	}
	// 	return $a;
	// }
	//找选项的名称
	public function findoption($val,$a)
	{
		//巨坑！
		$ra = trim($a);
		$ka = explode("'", $ra);
		$key=$ka[3];
		$keyword_list = trim($key);
        $keyword_arr = explode("\r\n", $keyword_list);
        $result='';
        foreach ($keyword_arr as $key => $value) {
            $b=explode("|", $value);
            if($b[1]==$val)
            {
				$result=$b[0];
				break;
            }
		}
		unset($keyword_arr);
		unset($b);
 
		 return  $result;
	}
	//文本转成列表
	public function convlist($val,$listkey)
	{
		$slist=array('name','id');
		$jlist=array('situation','time','j_describe','j_task','j_purpose','j_content','j_mode','j_process','j_condition','j_appraise','j_way','id');
		$xgzylist=array('title','url','id');
		$result=array();
		if($val)
		{
			$keyword_arr = explode(",\r\n", trim($val,','));
			foreach ($keyword_arr as $key => $value) {
				$temp=explode("|",$value);
				$rtemp=array();
				for ($i=0; $i < count($temp); $i++) { 
					switch ($listkey) {
						case 's_list':
							$rtemp[$slist[$i]]=$temp[$i];
							break;
						case 'j_list':
							$rtemp[$jlist[$i]]=$temp[$i];
							break;
						case 'xgzy':
							$rtemp[$xgzylist[$i]]=$temp[$i];
							break;
					}
				}
				array_push($result,$rtemp);
				unset($rtemp);
				// array_push($result, $value);
			}
			unset($keyword_arr);
			unset($temp);
		}

		return $result;
	}
	//转换出视频地址
	public function convrwsp($val)
	{
		$list=array('file','name');
		$result=array();
		if($val)
		{
		$keyword_arr = explode(":::", trim($val,','));
			foreach ($keyword_arr as $key => $value) {
				$temp=explode("|",$value);
				$rtemp=array();
			
				for ($i=0; $i < count($temp); $i++) { 
					if($list[$i]=='name')
					{
						$tt=findnameorext('/'.$temp[$i],0);
						//$tt=explode(".",$temp[$i]);
						$rtemp[$list[$i]]=$tt;
					}
					else
					{
						$rtemp[$list[$i]]=$temp[$i];
					}
					
				}
			
				array_push($result,$rtemp);
				unset($rtemp);
				// array_push($result, $value);
			}
			unset($keyword_arr);
			unset($temp);
		}
		//print_r($result);exit;
		return $result;
	}
	//修改成br换行
	public function conhc2br($value)
	{
		$str = str_replace("\r\n","<br />",$value);
		$str = htmlspecialchars_decode($str);
		return $str;
	}
	//素材分类函数 part1
	public function scbclss($list)
	{
		//$nlist=array('img'=>array(),'video'=>array(),'sound'=>array(),'other'=>array());
		foreach ($list as $key => $value) {
			$temp=$value['scwj']['val'];
			foreach ($temp as $key2 => $value2) {
				$res=$this->finscbtype($value2['file']);
				switch ($res) {
					case 'img':
						$list[$key]['scwj']['val'][$key2]['type']='img';
						//array_push($nlist['img'],$value);
						break;
					case 'video':
						$list[$key]['scwj']['val'][$key2]['type']='video';
						//array_push($nlist['video'],$value);
						break;
					case 'sound':
						$list[$key]['scwj']['val'][$key2]['type']='sound';
						//array_push($nlist['sound'],$value);
						break;
					default:
						$list[$key]['scwj']['val'][$key2]['type']='other';
						//array_push($nlist['other'],$value);
						break;
				}
			}
			unset($temp);
		}
		
		return $list;
	}
	//素材分类函数 part1
	public function finscbtype($obj)
	{
		$imgtype=array('jpg','png','psd');
		$videotype=array('mp4','flv');
		$soundtype=array('mp3','wav');
		//$add=$obj['scwj']['val'];
		$hz=findnameorext($obj,'1');
		$result='other';
		foreach ($imgtype as $key => $value) {
			if($value==$hz)
			{
				$result='img';
				break;
			}
		}
		foreach ($videotype as $key => $value) {
			if($value==$hz)
			{
				$result='video';
				break;
			}
		}
		foreach ($soundtype as $key => $value) {
			if($value==$hz)
			{
				$result='sound';
				break;
			}
		}
		return $result;
	}
	//转换radio的名称
	public function inttostr($result)
	{
		foreach ($result as $key => $value) {
			foreach ($value as $key2 => $value2) {
				$type=$value2['attr']['type'];
				if($type=='select'||$type=='radio')
				{
					$work=$this->findoption($value2['val'],$value2['attr']['setup']);
					$result[$key][$key2]['val']=$work;
					//$result[$key][$key2]['val']=$value2['val'];
				}
				if($key2=='s_list'||$key2=='j_list'||$key2=='xgzy')//下面记得要排除一下
				{
					$temp=$this->convlist($value2['val'],$key2);
					$result[$key][$key2]['val']=$temp;
				}
				if($key2=='rwsp')
				{
					$rwsp=$this->convrwsp($value2['val']);
					$result[$key][$key2]['val']=$rwsp;
				}
				if($key2=='scwj')
				{
					$scwj=$this->convrwsp($value2['val']);
					$result[$key][$key2]['val']=$scwj;
				}
				if($type=='textarea'&&$key2!='s_list'&&$key2!='j_list'&&$key2!='xgzy')
				{
					$br=$this->conhc2br($value2['val']);
					$result[$key][$key2]['val']=$br;
				}
			}
			unset($value2);
		}
		unset($value);
		return $result;
	}

	//根据项目id查看是否有权限
	public function getiskey($oid)
	{
		$isok=false;
		$getzyid=$this->getzyid($oid);
		$issc='0';
		$userid=$this->_userid;
                $quanx = json_decode($this->http('http://user.fjhgkj.com.cn/index.php?m=Home&c=Index&a=get_username',array('id'=>cookie('userid'),'type'=>cookie('groupid'))) ,'true') ;
                $dzy = trim($quanx['zy'],"[");
                $dzy = trim($dzy,"]");
                $ccc = str_replace('"', '', $dzy);
		$accarr=explode(',', $ccc);
                $schoolarr = explode(',', $quanx['school_zy']); 
		if($accarr)
		{
			foreach ($accarr as $key => $value) {

				if($value==$getzyid['pid'])
				{
					 
					$isok=true;
					break;
				}
			}
		}
		return $isok;

	}
        
	//数据重组 专为id12写 岗位id
	public function addquanxian($result,$gid)
	{
		$c=M('gangwei')->field('zyid')->where(array('id'=>$gid))->find();
		//$z=M('zhuanye')->field('title')->where(array('id'=>$c['zyid']))->find();
		$issc='0';
		$userid=$this->_userid;
		$quanx = json_decode($this->http('http://user.fjhgkj.com.cn/index.php?m=Home&c=Index&a=get_username',array('id'=>cookie('userid'),'type'=>cookie('groupid'))) ,'true') ;
                                $dzy = trim($quanx['zy'],"[");
                $dzy = trim($dzy,"]");
                $ccc = str_replace('"', '', $dzy);
		$accarr=explode(',', $ccc);
                $schoolarr = explode(',', $quanx['school_zy']); 
		$isok=false;
		if($accarr)
		{
			foreach ($accarr as $key => $value) {

				if($value==$c['zyid'])
				{
					 
					$isok=true;
					break;
				}
			}
			unset($value);

		}
		if($isok)
		{
			foreach ($result as $key1 => $value1) {
				$result[$key1]['fileonoff']['val']='true';
			}
			unset($value1);
		}
		else
		{
			$olist=M('f_item')->field('id')->where(array('gwid'=>$gid))->order('listorder asc')->select();
			$j=0;
			foreach ($result as $key2 => $value2) {
				$i=1;
				$xmid=0;
				foreach ($olist as $key3 => $value3) {
					if($value3['id']==$value2['id']['val'])
					{
						$xmid=$i;
					}
					$i++;
				}
				unset($value3);
				if($xmid==1)//项目一
				{
					if($j!=0)//第一个可以下载
					{
						$result[$key2]['fileonoff']['val']='false';
					}else
					{
						$result[$key2]['fileonoff']['val']='true';
					}
				}else
				{
					$result[$key2]['fileonoff']['val']='false';
				}
				$j++;
			}
			unset($value2);
			unset($olist);
		}
		return $result;
	}
	//数组重组 清除没有权限的项目  只保留项目一的第一个
	public function cleararrhref($result,$oid,$id)
	{
		 
		if($id=='24'||$id=='21'||$id=='22'||$id=='25'||$id=='14')
		{
			$userid=$this->_userid;
			$quanx = json_decode($this->http('http://user.fjhgkj.com.cn/index.php?m=Home&c=Index&a=get_username',array('id'=>cookie('userid'),'type'=>cookie('groupid'))) ,'true') ;
                        $dzy = trim($quanx['zy'],"[");
                        $dzy = trim($dzy,"]");
                        $ccc = str_replace('"', '', $dzy);
                        $accarr=explode(',', $ccc);
                        
                         $dzy1 = trim($quanx['school_zy'],"[");
                        $dzy2 = trim($dzy1,"]");
                        $ccc2 = str_replace('"', '', $dzy2);
                        $schoolarr=explode(',', $ccc2);
			$issc='0';//是否是老师 0不是
			if($id=='14')
			{
				foreach ($accarr as $key => $value) {
					//赋值老师有的专业
					foreach ($result as $key2 => $value2) {
						if($value2['id']['val']==$value)
						{
							$result[$key2]['acctype']['val']='in';
						}
					}
					unset($value2);
				}
				unset($value);
				if(cookie('groupid')!='1')
				{
					//老师状态 查询下该老师的学校还有什么专业有购买
					$newacc=$schoolarr;
					//赋值学校有的专业
					foreach ($newacc as $key => $value) {
						foreach ($result as $key2 => $value2) {
							if($value2['id']['val']==$value)
							{
								if(!$result[$key2]['acctype']['val'])
								{
									$result[$key2]['acctype']['val']='nin';
								}
								 
							}
						}
						unset($value2);
					}
					unset($value);
				}
				foreach ($result as $key => $value) {
					if(!$result[$key]['acctype']['val'])
					{
						$result[$key]['acctype']['val']='all';
					}
				}
				unset($value);
				return $result;
			}

			$getzyid=$this->getzyid($oid);
			$isok=false;//专业权限
			 
			if($accarr)
			{
				foreach ($accarr as $key => $value) {

					if($value==$getzyid['pid'])
					{
						 
						$isok=true;

					}
				}
				unset($value);
				if(cookie('groupid')!='1')
				{
					$newacc=$schoolarr;
					 
					foreach ($newacc as $key => $value) {
						if($value['zyid']==$getzyid['pid'])
						{
							$isok=true;

						}
					}
					unset($value);
				}

			}
			else
			{

			}
			 
			if(!$isok)
			{
				switch ($id) {
					case '24':
					//case '21':
					case '22':
						$i=0;
						foreach ($result as $key => $value) {
							if($getzyid['xmid']==1)//项目一
							{
								if($i!=0)//第一个可以下载
								{
									$result[$key]['fileonoff']['val']='false';
								}else
								{
									$result[$key]['fileonoff']['val']='true';
								}
							}else
							{
								$result[$key]['fileonoff']['val']='false';
							}
							$i++;
						}
						unset($value);
						break;
					case '21':
					    $i=0;
                                            $g=0;
						foreach ($result as $key => $value) {
                                                    if($getzyid['xmid']==1){
							if($g!=0){
                                                            $result[$key]['rwwjonoff']['val']='false';                         
                                                        }else{
                                                            $result[$key]['rwwjonoff']['val']='true';
                                                        }
                                                    }
                                                    $g++ ;
							$temp=$value['rwsp']['val'];
							if(count($temp)>0)
							{
								foreach ($temp as $key2 => $value2) {
									if($getzyid['xmid']==1)//项目一
									{
										if($i!=0)
										{
											$result[$key]['rwsp']['val'][$key2]['fileonoff']='false';
                                                                                         //$result[$key]['rwwjonoff']['val']='false';
										}
										else
										{
											$result[$key]['rwsp']['val'][$key2]['fileonoff']='true';
                                                                                       // $result[$key]['rwwjonoff']['val']='true';
										}
									}else
									{
										$result[$key]['rwsp']['val'][$key2]['fileonoff']='false';
									}
									$i++;
								}
								unset($value2);
							}
						}
						unset($value);
						break;
					case '25'://素材全部不可下载
						foreach ($result as $key => $value) {
							$temp=$value['scwj']['val'];
							if(count($temp)>0)
							{
								foreach ($temp as $key2 => $value2) {
									$result[$key]['scwj']['val'][$key2]['fileonoff']='false';
								}
								unset($value2);
							}
							 
							//$result[$key]['fileonoff']['val']='false';
						}
						unset($value);
						break;
					
				}
			}else
			{//给有权限的加上可下载
				switch ($id) {
					case '24':
					case '22':
						foreach ($result as $key => $value) {
							$result[$key]['fileonoff']['val']='true';
						}
						unset($value);
						break;
					case '21':
						foreach ($result as $key => $value) {
							$result[$key]['rwwjonoff']['val']='true';
							$temp=$value['rwsp']['val'];
							if(count($temp)>0)
							{
								foreach ($temp as $key2 => $value2) {
									$result[$key]['rwsp']['val'][$key2]['fileonoff']='true';
								}
								unset($value2);
							}
						}
						unset($value);
						break;
					case '25':
						foreach ($result as $key => $value) {
							$temp=$value['scwj']['val'];
							if(count($temp)>0)
							{
								foreach ($temp as $key2 => $value2) {
									$result[$key]['scwj']['val'][$key2]['fileonoff']='true';
								}
								unset($value2);
							}
							
							//$result[$key]['fileonoff']['val']='false';
						}
						unset($value);
						break;
				}
			}
		}
		return $result;
	}
	//根据项目Id活动专业Id和岗位Id
	public function getzyid($oid)
	{
		$o=M('f_item')->field('gwid,title')->where(array('id'=>$oid))->find();
		$c=M('gangwei')->field('zyid,title')->where(array('id'=>$o['gwid']))->find();
		$z=M('zhuanye')->field('title')->where(array('id'=>$c['zyid']))->find();
		$olist=M('f_item')->field('id')->where(array('gwid'=>$o['gwid']))->order('listorder asc')->select();
		$i=1;
		foreach ($olist as $key => $value) {
			if($value['id']==$oid)
			{
				$o['xmid']=$i;
			}
			$i++;
		}
		unset($olist);
		return array('pid'=>$c['zyid'],'pname'=>$z['title'],'cid'=>$o['gwid'],'cname'=>$c['title'],'oid'=>$oid,'oname'=>$o['title'],'xmid'=>$o['xmid']);

	}
	//按表获取或者用id获取使用
	//id=模块id pid=id获取表
	public function getarrbyid($id,$pid,$isarr=true,$field='*')
	{
		$bname=$this->modulefind($id);
		if($pid)
		{
			$list=M($bname)->field($field)->where(array('id'=>$pid))->order('listorder asc')->select();
		}
		else
		{
			$list=M($bname)->field($field)->order('listorder asc')->select();
		}
		 
		//return $list;
		 $result= $this->pushnewarr($id,$list,$isarr);
		 $out=$this->inttostr($result);
		 $out=$this->cleararrhref($out,$pid,$id);
		 //素材重组数组
		 if($id=='25')
		 {
			 $out=$this->scbclss($out);
		 }
		 if($id=='12')
		 {
			 $out=$this->addquanxian($out,$pid);
		 }
		 return $out;
		// foreach ($result as $key => $value) {
		// 	foreach ($value as $key2 => $value2) {
		// 		$type=$value2['attr']['type'];
		// 		if($type=='select'||$type=='radio')
		// 		{
		// 			$work=$this->findoption($value2['val'],$value2['attr']['setup']);
		// 			$result[$key][$key2]['val']=$work;
		// 			//$result[$key][$key2]['val']=$value2['val'];
		// 		}
		// 	}
		// }
		// return $result;
	}
	//除了专业以外的 用关联id使用 
	//id=模块id pid=关联id
	//13岗位 12项目 14专业 23电子教案表 22微课表 21任务表 24文档课件表 25素材表
	public function getarrbygid($id,$gid,$isarr=true,$field='*')
	{
		$bname=$this->modulefind($id);
		$a='zyid';
		switch ($id) {
			case '13':
				$a='zyid';
				break;
			case '12':
				$a='gwid';
				break;
			case '23':
				$a='xmid';
				break;
			case '22':
				$a='xmid';
				break;
			case '21':
				$a='xmid';
				break;
			case '24':
				$a='xmid';
				break;
			case '25':
				$a='xmid';
				break;
		}
		$data[$a]=$gid;
		$list=M($bname)->field($field)->where($data)->order('listorder asc')->select();


		//return $list;
		$result= $this->pushnewarr($id,$list,$isarr);
		$out=$this->inttostr($result);
		$out=$this->cleararrhref($out,$gid,$id);
		//素材重组数组
		if($id=='25')
		{
			$out=$this->scbclss($out);
		}
		if($id=='12')
		{
			$out=$this->addquanxian($out,$gid);
		}
		return $out;
	}
	//获取列表数量 
	public function getnumbygid($id,$gid)
	{
		$bname=$this->modulefind($id);
		$a='zyid';
		switch ($id) {
			case '13':
				$a='zyid';
				break;
			case '12':
				$a='gwid';
				break;
			case '23':
				$a='xmid';
				break;
			case '22':
				$a='xmid';
				break;
			case '21':
				$a='xmid';
				break;
			case '24':
				$a='xmid';
				break;
			case '25':
				$a='xmid';
				break;
		}
		$data[$a]=$gid;
		$count=M($bname)->where($data)->count();
		return $count;
	}
	//教学视频数量
	public function getjxspnum($id)
	{
		$count=0;
		$list=M('renwu')->field('rwsp')->where(array('xmid'=>$id))->select();
		foreach ($list as $key => $value) {
            if($value['rwsp'])
            {
                $rwsp=$this->convrwsp($value['rwsp']);
                $count+=count($rwsp);
            }
		}
		unset($list);
		return $count;
	}
	//素材数量
	public function getscbnum($id)
	{
		$count=0;
		$list=M('scb')->field('scwj')->where(array('xmid'=>$id))->select();
		foreach ($list as $key => $value) {
            if($value['scwj'])
            {
                $scwj=$this->convrwsp($value['scwj']);
                $count+=count($scwj);
            }
		}
		unset($list);
		return $count;
	}
	function p ($array){
		dump($array,1,'<pre>',0);	
	}
	//type html pdf
	public function conpdf($file,$type)
    {
        //$result='';
        $pdfre=$this->http("http://conv.fjhgkj.com.cn/ConvertersHandler.ashx",array('file'=>$file,'type'=>$type));
		$a=json_decode($pdfre,true);
		// $a['success']=true;
		// $a['file']='null';
        // if($a['success'])
        // {
        //     $result=$a['file'];
        // }
        return $a;
    }
    public function http($url, $data = NULL, $json = false)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($data)) {
            if($json && is_array($data)){
            $data = json_encode( $data );
            }
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            if($json){ //发送JSON数据
            curl_setopt($curl, CURLOPT_HEADER, 0);
            curl_setopt($curl, CURLOPT_HTTPHEADER,
            array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length:' . strlen($data))
            );
        }
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);

        if ($errorno) {
        return array('errorno' => false, 'errmsg' => $errorno);
        }
        curl_close($curl);
        return $res;
	}
	//zip
	function list_dir($dir){
    	$result = array();
    	if (is_dir($dir)){
    		$file_dir = scandir($dir);
    		foreach($file_dir as $file){
    			if ($file == '.' || $file == '..'){
    				continue;
    			}
    			elseif (is_dir($dir.$file)){
    				$result = array_merge($result, list_dir($dir.$file.'/'));
    			}
    			else{
    				array_push($result, $dir.$file);
    			}
    		}
    	}
    	return $result;
    }
	//调用$path = array("c:/wamp/www/log.txt","c:/wamp/www/weixin.class.php");
	function zipdown($datalist,$filename)
	{
		$filename=iconv("UTF-8", "GBK", $filename);
		//$datalist=list_dir('../');
		//$filename = "./zip/".$file.".zip"; //最终生成的文件名（含路径）  
		$result=array('msg'=>'成功','result'=>true); 
		if(!file_exists($filename)){   
		//重新生成文件   
			$zip = new ZipArchive();//使用本类，linux需开启zlib，windows需取消php_zip.dll前的注释   
			if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {   
				$result=array('msg'=>'无法打开文件，或者文件创建失败','result'=>false); 
				//exit('无法打开文件，或者文件创建失败');
			}   
			foreach( $datalist as $val){   
				if(file_exists($val['file'])){   
					$zip->addFile($val['file'], basename($val['file']));
					//$zip->renameName($val['oldname'],iconv("UTF-8", "GBK", $val['name']));
					$zip->renameName($val['oldname'],$val['name']);
				}   
			}   
			$zip->close();//关闭   
		}   
		if(!file_exists($filename)){   
			$result=array('msg'=>'无法找到文件','result'=>false); 
			//exit("无法找到文件"); //即使创建，仍有可能失败。。。。   
		}  
		return $result;
		// header("Content-Type: application/zip"); //zip格式的   
		// header('Content-disposition: attachment; filename='.basename($filename));
		// header('Content-Length:'.filesize ($filename));
		// ob_clean();
		// flush();
		// readfile($filename); 
		// // header("Cache-Control: public"); 
		// // header("Content-Description: File Transfer"); 
		// // header('Content-disposition: attachment; filename='.basename($filename)); //文件名   
		// // header("Content-Type: application/zip"); //zip格式的   
		// // header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件    
		// // header('Content-Length: '. filesize($filename)); //告诉浏览器，文件大小   
		// // @readfile($filename);
		// unlink($filename);//删除
	}
	function ajax_upload($path,$format='empty',$maxSize='52428800'){
		ini_set('max_execution_time', '0');
		// 去除两边的/
		$path=trim($path,'/');
		// 添加Upload根目录
		$path=strtolower(substr($path, 0,6))==='disk' ? ucfirst($path) : 'Disk'.$path;
		// 上传文件类型控制
		$ext_arr= array(
				'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
				'photo' => array('jpg', 'jpeg', 'png'),
				'flash' => array('swf', 'flv'),
				'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
				'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt','pptx', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2','pdf')
			);
		if(!empty($_FILES)){
			// 上传文件配置
			// $config=array(
			// 		'maxSize'   =>  $maxSize,               // 上传文件最大为50M
			// 		'rootPath'  =>  './',                   // 文件上传保存的根路径
			// 		'savePath'  =>  './'.$path.'/',         // 文件上传的保存路径（相对于根路径）
			// 		'saveName'  =>  array('uniqid',''),     // 上传文件的保存规则，支持数组和字符串方式定义
			// 		'autoSub'   =>  true,                   // 自动使用子目录保存上传文件 默认为true
			// 		'exts'      =>    isset($ext_arr[$format])?$ext_arr[$format]:'',
			// 	);
			// p($_FILES);
			// 实例化上传
			import("@.ORG.UploadFile"); 
			$upload = new UploadFile(); 
			$upload->maxSize=$maxSize;
			$upload->autoSub = true; 
			$upload->subType = 'date';
			$upload->dateFormat = 'Ym';
			//设置上传文件类型 
			$upload->allowExts = isset($ext_arr[$format])?$ext_arr[$format]:''; 
			//设置附件上传目录 
			$upload->savePath = './'.$path.'/'; 
			 //设置上传文件规则 
			$upload->saveRule = uniqid; 

			//$info=$upload->upload();
			// p($info);
			$data=array();
			if(!$upload->upload()){
				// 返回错误信息
				$error=$upload->getErrorMsg();
				$data['status']='0';
				$data['info']=$error;
				return $data;
			}else{
				$info=$upload->getUploadFileInfo(); 
				// 返回成功信息
				foreach($info as $file){
					$data['status']='1';
					$data['info']='成功';
					$data['name']=trim($file['name']);
					$data['size']=trim($file['size']);
					$data['extension']=trim($file['extension']);
					$data['savepath']=trim($file['savepath']);
					$data['savename']=trim($file['savename']);
					
					return $data;
				}     
				//echo json_encode($info);          
			}
		}
	}
	function getresources($type,$oid)
	{
		$where['uid']=$this->_userid;
		//$where['uid']=1;
		$where['type']=$type;
		if($oid)
		{
			$where['oid']=$oid;
		}
		$list=M('resources')->where($where)->select();
		$newlist=array();
		//$olist=array();
		foreach ($list as $key => $value) {
 
			 
			if(!$newlist[$value['oid']])
			{
				$newlist[$value['oid']]=$this->getzyid($value['oid']);
				$newlist[$value['oid']]['list']=array();
			}
			array_push($newlist[$value['oid']]['list'],$value);
		}
		return $newlist;
	}
	function qiniutime($url,$name,$key)//360
	{
		//$url="http://".$name.".fjhgkj.com.cn/1.png?v=1";
		$url = explode("?", $url);
		$path=basename($url[0]);
		$path="/".$name."_".$path;
		$time = time()+3600;
		$T=dechex($time);
		//$key="xxxx";
		$S=$key.$path.$T;
		$token = md5($S);
		$sign =strtolower($token);
		if(isset($url[1])){
			$url = "http://video".$name.".fjhgkj.com.cn".$path."?".$url[1]."&sign=".$sign."&t=".$T;
			 
		}else{
			$url = "http://video".$name.".fjhgkj.com.cn".$path."?sign=".$sign."&t=".$T;
			 
		}
		return $url;
	}
	public function findurl($moname,$acname)
	{
		$namelist=[['Index','material_details'],['Index','video'],['Index','pdf'],['Article','show'],['Feedback','join']];
		$result=true;
		foreach ($namelist as $key => $value) {
			if($moname==$value[0]&&$acname==$value[1])
			{
				$result=false;
				break;
			}
		}
		return $result;
	}
	public function extractzip($file,$path)
	{
		$zip=new ZipArchive;
		if($zip->open($file)===TRUE){
			$zip->extractTo($path);
			$zip->close();
			return true;
		}
		else
		{
			return false;
		}

	}
	public function duicuo($answer,$res)
	{
		 
		if(count($res)==0)
		{
			return  false;
		}
		else
		{
			if(count($res)>count($answer))
			{
				return false;
			}
			else
			{
				$result=array_diff($answer,$res);
				if(count($result)==0)
				{
					return true;
				}
				else
				{
					return false;
				}
			}
		}
	}
	//array('','');
	// function delDirAndFile($path, $delDir = FALSE) {
	// 	$handle = opendir($path);
	// 	if ($handle) {
	// 		while (false !== ( $item = readdir($handle) )) {
	// 			if ($item != "." && $item != "..")
	// 				is_dir("$path/$item") ? delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
	// 		}
	// 		closedir($handle);
	// 		if ($delDir)
	// 			return rmdir($path);
	// 	}else {
	// 		if (file_exists($path)) {
	// 			return unlink($path);
	// 		} else {
	// 			return FALSE;
	// 		}
	// 	}
	// }
	//  //array(array('file'=>'','name'=>''));
	// function copyfile($list,$dest)
	// {
	// 	$count=0;	 
	// 	$reslut=array();
	// 	foreach ($list as $key => $value) {
	// 		//$dest='./temp/'.$file.'/';
	// 		 //$this->delDirAndFile($dest,true);
	// 		if(!is_dir($dest))
	// 		{
	// 			mkdir(iconv("UTF-8", "GBK", $dest),0777,true); 
	// 		}
	// 		if(file_exists($value['file'])){
	// 			//$newfile=$dest.iconv("UTF-8", "GBK", $value['name']);   
	// 			if(copy($value['file'],$dest.iconv("UTF-8", "GBK", $value['name'])))
	// 			{
	// 				array_push($reslut,$dest.$value['name']);
	// 				$count++;
	// 			}
	// 		}
	// 	}
	// 	return $reslut;
	// }
	// function zipDir($basePath,$zipName){
	// 	//$zipName = "./zip/".$filename.".zip";
	// 	$result=array('msg'=>'成功','result'=>true); 
	// 	$zip = new ZipArchive();
	// 	$fileArr = [];
	// 	$fileNum = 0;
	// 	if(!file_exists($zipName)){   
	// 		if (is_dir($basePath)){
	// 			if ($dh = opendir($basePath)){
	// 				if ($zip->open($zipName, ZIPARCHIVE::CREATE)!==TRUE) {   
	// 					$result=array('msg'=>'无法打开文件，或者文件创建失败','result'=>false); 
	// 					//exit('无法打开文件，或者文件创建失败');
	// 				}   
	// 				//$zip->open($zipName,ZipArchive::CREATE);
	// 				while (($file = readdir($dh)) !== false){
	// 					if(in_array($file,['.','..',])) continue; //无效文件，重来
	// 					$file = iconv('gbk','utf-8',$file);
	// 					$extension = strchr($file,'.');
	// 					rename(iconv('UTF-8','GBK',$basePath.'\\'.$file), iconv('UTF-8','GBK',$basePath.'\\'.$fileNum.$extension));
	// 					$zip->addFile($basePath.'\\'.$fileNum.$extension,$fileNum.$extension);
	// 					$zip->renameName($fileNum.$extension,$file);
	// 					$fileArr[$fileNum.$extension] = $file;
	// 					$fileNum++;
	// 				}
	// 				$zip->close();
	// 				closedir($dh);
	// 				foreach($fileArr as $k=>$v){
	// 					rename(iconv('UTF-8','GBK',$basePath.'\\'.$k), iconv('UTF-8','GBK',$basePath.'\\'.$v));
	// 				}
	// 			}
	// 		}
	// 	}
	// 	if(!file_exists($zipName)){   
	// 		$result=array('msg'=>'无法找到文件','result'=>false); 
	// 		//exit("无法找到文件"); //即使创建，仍有可能失败。。。。   
	// 	}  
	// 	return $result;
		
	// }
	//zip
}
?>